/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package app;

import base.Download;
import exception.RepositoryException;
import base.RssPooler;
import base.Task;
import base.TorrentDownload;
import exception.TaskNotFoundException;
import facade.Facade;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 *
 * @author tacio
 */
public class TaskPooler extends TimerTask {

    private int repeatInterval;
    private Timer timer;

    public TaskPooler(int repeatInterval){
        this.repeatInterval = repeatInterval * 1000 * 60;
        this.timer = new Timer();
    }
   
    public void run() {
        try {
            ExecutorService cachedPool = Executors.newCachedThreadPool();
            Facade facade = Facade.getFacade();
            SAXBuilder builder = new SAXBuilder();
            Document tasksXml = builder.build(TaskPooler.class.getResourceAsStream("/resources/Tasks.xml"));
            List<Element> taskList = tasksXml.getRootElement().getChildren("task");
            for (Element element : taskList) {
                Task task = facade.search(element.getAttributeValue("name"));
                RssPooler pooler = new RssPooler(task);
                URL episode = pooler.pool();
                if (episode != null && !facade.downloadExists(task, episode)) {
                    cachedPool.execute(new TorrentDownload(episode));
                    Download download = new Download(task.getName());
                    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    Date date = new Date();
                    download.setDate(dateFormat.format(date));
                    download.setTorrentName(episode.toString());
                    ArrayList<Download> downloads = new ArrayList<Download>();
                    downloads.add(download);
                    task.setDownloads(downloads);
                    facade.updateTask(task);
                }
            }
            cachedPool.shutdown();
        } catch (JDOMException ex) {
            Logger.getLogger(TaskPooler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TaskPooler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RepositoryException ex) {
            System.out.println(ex.getMessage());
        } catch (TaskNotFoundException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public void stop() {
        this.getTimer().cancel();
    }

    /**
     * @return the repeatInterval
     */
    public int getRepeatInterval() {
        return repeatInterval;
    }

    /**
     * @return the timer
     */
    public Timer getTimer() {
        return timer;
    }
}

